import React, { createRef, Component, RefObject } from 'react'
import { Layout, Row, Col, Progress } from 'antd'
import { ipcRenderer } from 'electron'
import { bindAll } from 'underscore'
import Mjpg from '../../utils/mjpg'
import { ipctype } from '../../main/interface'
import { ChildProcessWithoutNullStreams } from 'child_process'
import { delay } from '../../utils/time'
import videoleft from '../../assets/videoleft.png'
import videoright from '../../assets/videoright.png'
import l6 from '../../assets/l-6.png'
import l7 from '../../assets/l-7.png'
import { ReloadOutlined } from '@ant-design/icons'
import { Zwifi } from '../demo'
import Buton from '../d/buton'
import { facetype } from '../types'
const { Content, Footer, Sider, Header } = Layout

type Props = {
  display: "block" | "none",
  setdis: (display: "block" | "none") => void,
  error: Function,
  bashou: string,
  start: boolean
  setstart: (start: boolean) => void,
  seticon: (icon: string) => void,
  icon?: string,
  type: facetype,
  fullscreen(): void,
  setfacetype(data: facetype): void,
  wifi: number,
  replace(): void
}

type State = {
  video: RefObject<HTMLImageElement>,
  trak: Boolean,
  timer: number | NodeJS.Timeout,
  timer2: number | NodeJS.Timeout,
  ls?: ChildProcessWithoutNullStreams,
  imageNr: number,
  fram: number,
  nust: boolean,
  timer3: number | NodeJS.Timeout,
  ur: string,
}




export default class Video11 extends Component<Props, State> {
  constructor(prop: Props) {
    super(prop)
    const ls = Mjpg()
    bindAll(this, 'stop1', '_canvasimage')
    this.state = {
      video: createRef<HTMLImageElement>(),
      trak: false,
      timer: 0,
      ls,
      imageNr: 0,
      fram: 0,
      timer2: 0,
      nust: false,
      timer3: 0,
      ur: ''
    }
    window.addEventListener('beforeunload', () => {
      ls?.kill('SIGHUP')
    })
  }

  componentDidUpdate(_prevProps: Props, _prevState: State) {
    if (this.props.start !== _prevProps.start && this.props.start) {
      this._canvasimage()
    }
  }

  stop1() {
    if (typeof this.state.timer == 'number') {
      clearInterval(this.state.timer)
    }
    this.setState({
      trak: false
    })
  }



  async _canvasimage() {
    const { video } = this.state
    const { type } = this.props
    const ca = document.getElementById('canvas') as HTMLCanvasElement
    this.props.seticon('#icondengdai')
    const context = ca.getContext('2d')
    try {
      if (video.current) {
        ca.width = video.current.width
        ca.height = video.current.height
        context?.drawImage(video.current, 0, 0, ca.width / 1.3, ca.height / 1.3);
        var data = ca.toDataURL('image/png').slice(22)
        this.props.setstart(false)
        ipcRenderer.send(ipctype['baidu-gesture'], data, type)
      }
    } catch (e) {
      const { video } = this.state
      if (video.current) {
        video.current.src = "http://127.0.0.1:8080/?action=stream&n=" + Math.random()
      }
      await delay(300)
      this._canvasimage()
    }

  }

  async componentDidMount() {
    await delay(1000)
    const { video } = this.state
    if (video.current) {
      video.current.src = "http://127.0.0.1:8080/?action=stream"
    }
    this._canvasimage()
  }

  componentWillUnmount() {
    // this.state.trak?.stop()
    this.state.ls?.kill()
    cancelAnimationFrame(this.state.fram)
    if (typeof this.state.timer == 'number') {
      clearInterval(this.state.timer)
    }
    if (typeof this.state.timer2 == 'number') {
      clearInterval(this.state.timer2)

    }
    if (typeof this.state.timer3 == 'number') {
      clearInterval(this.state.timer3)
    }
  }

  render() {
    const { type, fullscreen, setfacetype, wifi, replace } = this.props
    const { video } = this.state
    const z: Zwifi[] = [{
      color: '#52c41a',
      percent: 25,
    },
    {
      color: '#00ff00',
      percent: 58,
    },
    {
      color: '#26d8f1',
      percent: 100,
    }
    ]
    let x: Zwifi = z[2]
    if (wifi < 100) {
      x = z[2]
    } else if (wifi < 1000) {
      x = z[1]
    } else {
      x = z[0]
    }
    let n = wifi
    if (wifi > 9999) {
      n = 9999
    }
    return <>
      <Header onDoubleClick={fullscreen}>
        <Buton type={type} settype={setfacetype}></Buton>
        <div className="header-right">
          <Layout>
            {n === 9999 ?
              <Sider width="270" style={{ textAlign: 'center' }} className="wifi">
                <span style={{ paddingRight: '20px', display: 'inline-block' }} >
                  网络超时
                                <svg className="icon" aria-hidden="true">
                    <use xlinkHref="#iconxinhao-signal-fill"></use>
                  </svg>
                </span>
                <span className="text-danger">
                  0ms
                            <svg className="icon" aria-hidden="true">
                    <use xlinkHref="#iconduanwang"></use>
                  </svg>
                </span>

              </Sider>
              :
              <Sider width="270" className="wifi">
                网络延迟
                            <span>
                  <Progress percent={x.percent} steps={3} size="small" showInfo={false} strokeColor={x.color} ></Progress>
                  {n}ms
                            </span>
              </Sider>
            }
            <Content onClick={replace} className="rex">
              <ReloadOutlined />
        &nbsp;
        重启
    </Content>
          </Layout>

        </div>



      </Header>
      <Content className="left" >
        <Row >
          <Col span={12} >
            <div className="img position-relative image-b" >
              <div className="position-absolute abget " >
                <svg className="icon" aria-hidden="true">
                  <use xlinkHref={this.props.icon ? this.props.icon : '#iconluxiang'}></use>
                </svg>
              </div>
              <img id="video" ref={video} width="320" src="http://127.0.0.1:8080/?action=stream" crossOrigin="anonymous" ></img>
            </div>
          </Col>
          <Col span={12} >
            <div className="img image-a" >
              <h3>手势识别</h3>
              <img id="img" src="" alt="" />
              <canvas id="canvas" width="425" height="475.25"  ></canvas>
            </div>
          </Col>
        </Row>
      </Content>
      <Footer>
        <Row>
          <Col span={12} className="text-center" >
            <img src={type === 'head' ? videoleft : l7} alt="" />
          </Col>
          <Col span={12} className="text-right">
            <img src={type === 'head' ? videoright : l6} alt="" />
          </Col>
        </Row>
      </Footer>
    </>
  }
}
